package com.jsbs.iam.user.service.impl;

import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.param.AccountInfoDto;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.user.entity.IamUserInfo;
import com.jsbs.iam.user.feign.IdentFeignInterface;
import com.jsbs.iam.user.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AccountServiceImpl {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IdentFeignInterface identFeignInterface;

    /**
     * 功能描述：自动创建账号
     * @param userInfoList
     */
    @Async("asyncExecutor")
    public void autoCreateAccount(List<IamUserInfo> userInfoList) {
        if (CollectionUtils.isEmpty(userInfoList)) {
            return;
        }
        List<AccountInfoDto> infoDtos = new ArrayList<>();
        //封装数据
        userInfoList.forEach(item -> {
            AccountInfoDto infoDto = new AccountInfoDto();
            BeanUtils.copyProperties(item, infoDto);
            // 默认账户密码 手机号后6位 加密入库
            infoDto.setPassword(DigestUtils.md5DigestAsHex(item.getPhone().substring(item.getPhone().length() - 6).getBytes()));
            infoDtos.add(infoDto);
        });
        // 调账户中心自动创建账户
        Result result = identFeignInterface.autoCreateAccount(infoDtos);
        if (Objects.isNull(result) || !result.isSuccess()) {
            log.info("Route=>AccountServiceImpl method=autoCreateAccount 自动创建账户发生异常result:{}", Json.toJsonString(result));
            throw new RuntimeException("自动创建账户异常");
        }
        log.info("Route=>AccountServiceImpl method=autoCreateAccount 自动创建账户结果：{}", Json.toJsonString(result));
        // 获取自动创建成功的用户ID
        List<String> userCodes = (List<String>) result.getData();
        if (CollectionUtils.isNotEmpty(userCodes)) {
            // 批量更新为已开通账户
            userInfoMapper.updateByUserCode(userCodes);
        }
    }
}
